package com.hh85.updateapk;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;
import java.util.ArrayList;

public class OpenFileUtils {


    public static void install(Context context, File apkFile) {

        if (context == null ) {

            return;
        }
        if(apkFile == null){

            return;
        }
        if(!apkFile.exists()){

            Toast.makeText(context,"文件不存在"+apkFile,Toast.LENGTH_SHORT).show();
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {


            setup(context, FileProvider.getUriForFile(context, context.getPackageName()+".fileProvider", apkFile));
        } else {

            // 这一步很重要，android 6.0 及以下，需要获取文件全路径的文件权限
            chmodFullFile(context, apkFile);
        }
    }

    /**
     * 修改file全路径的读写权限
     *
     * @param file
     */
    private static void chmodFullFile(final Context context, final File file) {
        if (file == null) {
            return;
        }
        ArrayList<String> commands = new ArrayList<>();
        getAllCommand(commands, file);
        if (commands.size() > 0) {
            String[] c = new String[commands.size()];
            for (int i = 0; i < commands.size(); i++) {
                c[i] = commands.get(i);
                System.out.println(commands.get(i));
            }
            setup(context, Uri.fromFile(file));
        }

    }

    private static void getAllCommand(ArrayList<String> command, File file) {
        if (file == null) {
            return;
        }
        command.add("chmod 777 " + file.getAbsolutePath());
        getAllCommand(command, file.getParentFile());
    }

    private static void setup(Context context,Uri  apkUri){


        Intent intent = new Intent();
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
